package net.sharpf2.api.types;

import java.awt.Point;
import java.awt.Polygon;
import java.util.ArrayList;
import net.sharpf2.sfcore.client.SDModel;
import net.sharpf2.api.util.Mathematics;
import net.sharpf2.api.world.Ground;
import net.sharpf2.api.world.Space;

/**
 *
 * @author Rick van Biljouw
 */
public class Model {
    private int[] verticesX, verticesY, verticesZ;
    private short[] trianglesX, trianglesY, trianglesZ;
    private SDModel model;
    private Point position;

    public Model(SDModel model, Point position) {
        this.model = model;
        this.position = position;
    }

    public SDModel getModel() {
        return this.model;
    }

    public Polygon[] getPolygons() {
        ArrayList<Polygon> polys = new ArrayList<Polygon>();

        verticesX = getModel().getVerticesX().clone();
        verticesY = getModel().getVerticesY().clone();
        verticesZ = getModel().getVerticesZ().clone();
        trianglesX = getModel().getFaceA().clone();
        trianglesY = getModel().getFaceB().clone();
        trianglesZ = getModel().getFaceC().clone();

        //setRotation((64 * 128) & 0x3fff);
        for (int i = 0; i < trianglesX.length; i++) {
            if (i >= trianglesY.length && i >= trianglesZ.length) {
                return null;
            }
            Point x = Space.get2DCoordinate(position.x + verticesX[trianglesX[i]], position.y + verticesZ[trianglesX[i]], getBaseHeight() + verticesY[trianglesX[i]]);
            Point y = Space.get2DCoordinate(position.x + verticesX[trianglesY[i]], position.y + verticesZ[trianglesY[i]], getBaseHeight() + verticesY[trianglesY[i]]);
            Point z = Space.get2DCoordinate(position.x + verticesX[trianglesZ[i]], position.y + verticesZ[trianglesZ[i]], getBaseHeight() + verticesY[trianglesZ[i]]);
            if (x.x > 0 && x.y > 0 && y.x > 0 && y.y > 0 && z.x > 0 && z.y > 0) {
                int xx[] = {
                    x.x, y.x, z.x
                };
                int yy[] = {
                    x.y, y.y, z.y
                };
                polys.add(new Polygon(xx, yy, 3));
            }
        }
        return polys.toArray(new Polygon[polys.size()]);
    }

    public int getBaseHeight() {
        return Ground.getHeight(position.x, position.y);
    }

    protected void setRotation(int orientation) {
        int sin = Mathematics.SIN_TABLE[orientation];
        int cos = Mathematics.COS_TABLE[orientation];
        for (int i = 0; i < verticesX.length; i++) {
            int i1 = verticesY[i] * sin + verticesX[i] * cos >> 15;
            verticesY[i] = verticesY[i] * cos - verticesX[i] * sin >> 15;
            verticesX[i] = i1;
        }
    }
}
